<?php

namespace backend\controllers;

use Yii;
use backend\models\Image;
use backend\models\ImageSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\UploadForm;

use liangzoe\mobilesmser\TextSmser;
use yii\web\UploadedFile;
use PHPThumb\GD;
use yii\db\Query;
use yii\web\ForbiddenHttpException;

/**
 * ImageController implements the CRUD actions for Image model.
 */
class ImageController extends Controller
{
	
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('image-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all Image models.
     * @return mixed
     */
    public function actionIndex()
    {
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	return $this->render('index',[
    			'model' => $model,
    			]);
    	/*
        $searchModel = new ImageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);*/
    }
	
    public function actionSelectTz()
    {
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	return $this->render('select_tz',[
    			'model' => $model,
    			]);
    }
    /**
     * Displays a single Image model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Image model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Image();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Image model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Image model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Image model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Image the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Image::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    /**
     * 分页显示图片
     * @param unknown $pageNum
     * @param unknown $img_type
     */
    public function actionShowImage($page,$search,$tag)
    {
    	
    	//$page = intval($_POST['pageNum']); //当前页
    	//$page = $page;
    	if($tag == 'type')
    	$total = Image::find()->where(['type'=>$search])->count(); //总记录数
    	if($tag == 'name')
    		$total = Image::findBySql("select * from sys_image where name like '%".$search."%'")->count();
    		//$total = Image::findBySql("select * from sys_image where name like ':search'",[':search'=>$search])->count();
    	/*	$total = (new Query())
    		->select('*')
    		->from('sys_image')
    		->where('name like "%:search%"', [':search' => $search])
    		->count();*/

    	//$total = Image::find()->where(['name'=>$search])->count();
    	
    	
    	$pageSize = 10; //每页显示数
    	$totalPage = ceil($total/$pageSize); //总页数
    	
    	$startPage = $page*$pageSize;//开始记录
    	//构造数组
    	
    	$arr['total'] = $total;
    	$arr['pageSize'] = $pageSize;
    	$arr['totalPage'] = $totalPage;
    	if($tag == 'type')
    	$result = Image::findBySql("select * from sys_image where type=".$search." order by id desc limit ". $startPage . "," . $pageSize )->all();
    	if($tag == 'name')
    		$result = Image::findBySql("select * from sys_image where name like '%".$search."%' order by id desc limit ". $startPage . "," . $pageSize )->all();
    	 
    	if($result !=null)
    	{
	    	foreach ($result as $value )
	    	{
	    		$arr['list'][] = array(
	    				'id' => $value['id'],
	    				'type' => $value['type'],
	    				'name' => $value['name'],
	    				'url' => $value['url'],
	    				'width' => $value['width'],
	    				'height' => $value['height'],
	    				
	    		);
	    	}
	    	echo json_encode($arr); //输出JSON数据
    	}
    	
    	else {
    		$arr['list'][] = array(
    				'id' => '',
    				'type' => '',
    				'name' => '',
    				'url' => '',
    				'width' => '',
    				'height' => '');
    		
    		echo json_encode($arr);
    	}
    	
    	
    }
    
    /**
     * 上传图片
     * @param unknown $id
     * @return Ambigous <string, string>
     */
    public function actionUploadImage($type_id)
    {
    	$this->layout = 'main_small';
    	$model = new UploadForm();
    	$model->scenario = 'need_file_name';
    	 

    	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
    		$model->file = UploadedFile::getInstance($model, 'file');
    		
    		if ($model->file && $model->validate()) {
    			$arr = $this->save_image_to_files($model,$type_id);  			 
    			if($arr !== null){
    				//echo $arr['img_show'];
    				return $this->render('upload_img',[
    						'model' => $model,
    						'arr_img' => $arr,
    					]);
    			}else{
    				echo '上传失败';
    		
    			}
    		}
    	}
    	 
    	return $this->render('upload_img', [
    			'model' => $model,
    			 
    			]);
    }
    
    /**
     * 共用--存入数据到文件夹，并获取缩略图，三种图片的id
     * @param unknown $model
     * @param number $width1
     * @param number $height1
     * @param number $width2
     * @param number $height2
     * @return multitype:string boolean Ambigous <boolean, number>
     */
    public function save_image_to_files($model,$file_menu)
    {
    	 
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3); 	 
    	$uuid_file_name =  substr($uuid, 12,20); 	 
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    	   	
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置   	 
    	$model->file->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    	$image_name = $model->name;
    	
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_url_id = $this->newimage($image_name,$image_addr, $file_menu, $image_w, $image_h);
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->file->extension; 
    	
    	//生成缩略图并记录到数据库（中图）,大于990的时候
    	if( $image_w / 2 >= 990)
    	{	    
    		$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension); //原图
	    	//$thumb->resize($width1,$height1);
	    	$thumb->resizePercent(50);
	    	$file_save_addr_thumb = $file_save_addr.'_1';//实际位置
	    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension);
	    
	    	$image_addr_thumb = $file_save_addr_thumb.'.'.$model->file->extension;
	    	$image_url_thumb = $file_menu;//虚拟目录（图片类别）
	    	$image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[0];
	    	$image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->file->extension)[1];
	    
	    	$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_thumb.'.'.$model->file->extension.'">';
	    	$img_thumb_url = $file_save_addr_thumb.'.'.$model->file->extension;
    	}
    	else 
    	{
    		$img_thumb_url = '';
    	}

    	
    	//生成缩略图并记录到数据库（小图）
    	if( $image_w /4 >=  300)
    	{
	    	//$thumb->resize($width2,$height2);
	    	$small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);//原图
	    	$small->resizePercent(25);
	    	$file_save_addr_small = $file_save_addr.'_2';//实际位置
	    	$small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension);
	        
	    	$image_addr_small = $file_save_addr_small.'.'.$model->file->extension;
	    	$image_url_small = $file_menu;//虚拟目录（图片类别）
	    	$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[0];
	    	$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->file->extension)[1];
	    
	    	$img_small_id = $this->newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_small.'.'.$model->file->extension.'">';
	    	$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
	    	$img_small_url = $file_save_addr_small.'.'.$model->file->extension;
	    	
    	}
    	else
    	{
    		$img_small_url= '';
    	}
    	return array('img_url'=>$img_url,'img_thumb_url'=>$img_thumb_url,'img_small_url'=>$img_small_url,'img_show'=>$img_show);
    	//return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    }
    /*
     *     public function save_image_to_files($model,$file_menu)
    {
    	 
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3);
    	 
    	$uuid_file_name =  substr($uuid, 12,20);
    	 
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    	 
    	
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置
    	 
    	$model->file->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    	$image_name = $model->name;
    	
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_url_id = $this->newimage($image_name,$image_addr, $image_url, $image_w, $image_h);
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->file->extension; 
    	//生成缩略图并记录到数据库（中图）
    	$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    
    	//$thumb->resize($width1,$height1);
    	$thumb->resizePercent(50);
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name.'_1';//实际位置
    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;//虚拟目录（图片类别）
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_thumb_id = $this->newimage($image_name.'_thumb',$image_addr, $image_url, $image_w, $image_h);
    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_thumb_url = $file_save_addr.'.'.$model->file->extension;
    	//生成缩略图并记录到数据库（小图）
    	//$thumb->resize($width2,$height2);
    	$thumb->resizePercent(50);
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name.'_2';//实际位置
    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension);
    
    
    	$image_addr = $file_save_addr.'.'.$model->file->extension;
    	$image_url = $file_menu;//虚拟目录（图片类别）
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->file->extension)[1];
    
    	$img_small_id = $this->newimage($image_name.'_small',$image_addr, $image_url, $image_w, $image_h);
    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->file->extension.'">';
    	$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
    	$img_small_url = $file_save_addr.'.'.$model->file->extension;
    	//return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    	
    	return array('img_url'=>$img_url,'img_thumb_url'=>$img_thumb_url,'img_small_url'=>$img_small_url,'img_show'=>$img_show);
    	
    }
     * */
    /**
     * 共用-在数据表sys_image写入新图片
     * @param unknown $image_addr
     * @param unknown $image_url
     * @param unknown $image_w
     * @param unknown $image_h
     * @return boolean
     */
    public function newimage($image_name,$image_addr,$file_menu,$image_w,$image_h)
    {
    	$model_image = new Image();
    	$model_image->name = $image_name;
    	$model_image->url = $image_addr;
    	$model_image->type = $file_menu;
    	$model_image->width = $image_w;
    	$model_image->height = $image_h;
		$model_image->update_time = time();
    	if($model_image->save())
    	{
    		return $model_image->id;
    		
    	}
    }
    /*
     * 脚批量修改时，可以用
    public function actionChangeSmallimage()
    {
    	
    	$model = Image::findBySql('SELECT * FROM sys_image WHERE url not like "%\_2%" and url not like "%\_1%" and id>19000 and id <= 21000')->all();
		
    	//var_dump($model);
    	foreach ($model as $value)
    	{
    	//	echo $value->url;
    		
	    	$file_name = explode('.', $value->url)[0]."_2";//小图的名字
	    	$file_extend = explode('.', $value->url)[1];//小图的扩展名
	    	$file_name_save = implode('.', array($file_name,$file_extend)); //存入文件的名称 url
	    	
	    	$model_small = Image::findOne(['url' => $file_name_save]);
	    	echo $file_name_save;
	    	if($model_small != null)
	    	{
	    			//有小图的情况下，传入小图
	    			
	    			$small = new GD(Yii::getAlias('@webroot').'/'.$value->url);//原图		
	    			$small->resizePercent(25);
	    			$small->save(Yii::getAlias('@webroot').'/'.$file_name_save); //存入文件夹
	    			 //获取图片的宽和高
	    			$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_name_save)[0]; //获取图片的宽
	    			$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_name_save)[1]; //获取图片的高
					//更改信息
	    			$model_small->width = $image_w_small;
	    			$model_small->height = $image_h_small;
	    			if($model_small->save())
	    			{
	    				echo 'ok';
	    				//echo '<img src='.$model_small->url.' />'.$model_small->width.'X'.$model_small->height;
	    			}
	    	}  
    	}
    	echo '完成本批';
    }
    */
    public function actionSelectImageTypeid()
    {
    	$model = new UploadForm();
    	$model->scenario = 'upload_img';
    	$this->layout = 'main_image';
    	return $this->render('select_image_type',[
    			'model' => $model,
    			]);
    		
    }
    public function actionWriteTypeidToCookie($typeid)
    {
    	
    	$cookies = Yii::$app->response->cookies;
    	$cookies->add(new \yii\web\Cookie([
    			'name' => 'image_typeid',
    			'value' => $typeid,
    			]));
    	
    	$cookies = Yii::$app->request->cookies;
    	if(isset($cookies['image_typeid']))
    	{
    		$image_typeid = $cookies['image_typeid']->value;
    		//echo $image_typeid;
    		
    	}
    	return $image_typeid;
    }
	    /*选择套装存入cookies*/
    public function actionWriteTzToCookie()
    {
    	var_dump($_GET['arr_tz']);
    	/*
    	$arr_tz_new = array();
    	foreach ($_GET as $k => $v){
    		if($k == 'arr_tz'){
    			array_push($arr_tz_new, $v);
    		}
    	}
    	var_dump($arr_tz_new);
    	$cookies = Yii::$app->response->cookies;
    	$cookies->add(new \yii\web\Cookie([
    			'name' => 'arr_tz',
    			'value' => $arr_tz_new,
    			]));
    	 
    	$cookies = Yii::$app->request->cookies;
    	if(isset($cookies['arr_tz']))
    	{
    		//$tz_list = implode(',',$cookies['arr_tz']->value);
    		$tz_list = $cookies['arr_tz']->value;
    		var_dump($tz_list);
    		//echo $image_typeid;
    
    	}*/
    	return 1;
    }
}
